package com.duojuhe.coremodule.info.service.impl;

import com.duojuhe.common.annotation.DataScopeFilter;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.constant.DataScopeConstants;
import com.duojuhe.common.enums.SystemEnum;
import com.duojuhe.common.exception.base.DuoJuHeException;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.info.entity.InfoCategory;
import com.duojuhe.coremodule.info.entity.InfoNews;
import com.duojuhe.coremodule.info.mapper.InfoCategoryMapper;
import com.duojuhe.coremodule.info.mapper.InfoNewsMapper;
import com.duojuhe.coremodule.info.pojo.dto.news.*;
import com.duojuhe.coremodule.info.service.InfoNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class InfoNewsServiceImpl  extends BaseService implements InfoNewsService {
    @Resource
    private InfoCategoryMapper infoCategoryMapper;

    @Resource
    private InfoNewsMapper infoNewsMapper;

    /**
     * 【信息详情】根据信息发布ID获取信息详情
     * @param req
     * @return
     */
    @Override
    public ServiceResult<QueryInfoNewsRes> queryInfoNewsResByNewsId(InfoNewsIdReq req) {
        QueryInfoNewsRes newsRes = infoNewsMapper.queryInfoNewsResByNewsId(req.getNewsId());
        if (newsRes==null || SystemEnum.IS_DELETE.YES.getKey().equals(newsRes.getIsDelete())){
            throw new DuoJuHeException(ErrorCodes.PARAM_ERROR);
        }
        return ServiceResult.ok(newsRes);
    }

    /**
     * 【分页查询信息发布list】分页查询信息发布list
     * @param req
     * @return
     */
    @DataScopeFilter
    @Override
    public ServiceResult<PageResult<List<QueryInfoNewsPageRes>>> queryInfoNewsPageResList(QueryInfoNewsPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,updateTime desc,createTime desc, newsId desc");
        List<QueryInfoNewsPageRes> list = infoNewsMapper.queryInfoNewsPageResList(req,SystemEnum.IS_DELETE.NO.getKey());
        return PageHelperUtil.returnServiceResult(req, list);
    }

    /**
     * 【分页查询我发布的信息list】分页查询我发布的信息list
     * @param req
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.SELF_DATA)
    @Override
    public ServiceResult<PageResult<List<QueryMyInfoNewsPageRes>>> queryMyInfoNewsPageResList(QueryMyInfoNewsPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,updateTime desc,createTime desc, newsId desc");
        List<QueryMyInfoNewsPageRes> list = infoNewsMapper.queryMyInfoNewsPageResList(req,SystemEnum.IS_DELETE.NO.getKey());
        return PageHelperUtil.returnServiceResult(req, list);
    }


    /**
     * 【分页查询我的回收站信息list】分页查询我的回收站信息list
     * @param req
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.SELF_DATA)
    @Override
    public ServiceResult<PageResult<List<QueryMyInfoNewsPageRes>>> queryRecycleInfoNewsPageResList(QueryMyInfoNewsPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,updateTime desc,createTime desc, newsId desc");
        List<QueryMyInfoNewsPageRes> list = infoNewsMapper.queryMyInfoNewsPageResList(req,SystemEnum.IS_DELETE.YES.getKey());
        return PageHelperUtil.returnServiceResult(req, list);
    }

    /**
     * 【保存】信息发布信息
     * @param req
     * @return
     */
    @Override
    public ServiceResult saveInfoNews(SaveInfoNewsReq req) {
        //当前登录人
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //检查分类
        checkInfoCategoryId(req.getCategoryId(),userTokenInfoVo.getTenantId());
        //当前时间
        Date nowDate = new Date();
        //信息id
        String newsId = UUIDUtils.getUUID32();
        //构建信息对象
        InfoNews infoNews = new InfoNews();
        infoNews.setNewsId(newsId);
        infoNews.setCategoryId(req.getCategoryId());
        infoNews.setNewsTitle(req.getNewsTitle());
        infoNews.setNewsThumbnail(req.getNewsThumbnail());
        infoNews.setIntroduction(req.getIntroduction());
        infoNews.setNewsContent(req.getNewsContent());
        infoNews.setSort(req.getSort());
        infoNews.setIsDelete(SystemEnum.IS_DELETE.NO.getKey());
        infoNews.setCreateTime(nowDate);
        infoNews.setCreateDeptId(userTokenInfoVo.getCreateDeptId());
        infoNews.setCreateUserId(userTokenInfoVo.getUserId());
        infoNews.setTenantId(userTokenInfoVo.getTenantId());
        infoNews.setUpdateTime(nowDate);
        infoNews.setUpdateUserId(userTokenInfoVo.getUserId());
        //设置允许查询权限
        infoNews.setDataAllowAuth(SystemEnum.DATA_ALLOW_AUTH.ALL_AUTH.getKey());
        infoNewsMapper.insertSelective(infoNews);
        return ServiceResult.ok(newsId);
    }

    /**
     * 【修改】信息发布信息
     * @param req
     * @return
     */
    @Override
    public ServiceResult updateInfoNews(UpdateInfoNewsReq req) {
        InfoNews infoNews = infoNewsMapper.selectByPrimaryKey(req.getNewsId());
        if (infoNews==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        String userId = getCurrentLoginUserId();
        if (!userId.equals(infoNews.getCreateUserId())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //检查分类
        checkInfoCategoryId(req.getCategoryId(),infoNews.getTenantId());
        //当前时间
        Date nowDate = new Date();
        InfoNews updateInfoNews = new InfoNews();
        updateInfoNews.setNewsId(infoNews.getNewsId());
        updateInfoNews.setCategoryId(req.getCategoryId());
        updateInfoNews.setNewsTitle(req.getNewsTitle());
        updateInfoNews.setNewsThumbnail(req.getNewsThumbnail());
        updateInfoNews.setIntroduction(req.getIntroduction());
        updateInfoNews.setNewsContent(req.getNewsContent());
        updateInfoNews.setSort(req.getSort());
        updateInfoNews.setUpdateTime(nowDate);
        updateInfoNews.setUpdateUserId(userId);
        //设置允许查询权限
        updateInfoNews.setDataAllowAuth(SystemEnum.DATA_ALLOW_AUTH.ALL_AUTH.getKey());
        infoNewsMapper.updateByPrimaryKeySelective(updateInfoNews);
        return ServiceResult.ok(req.getNewsId());
    }

    /**
     * 【彻底删除】根据信息发布ID彻底删除信息发布，注意一次仅能彻底删除一个信息发布
     * @param req
     * @return
     */
    @Override
    public ServiceResult deleteInfoNewsByNewsId(InfoNewsIdReq req) {
        InfoNews infoNews = infoNewsMapper.selectByPrimaryKey(req.getNewsId());
        if (infoNews==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        String userId = getCurrentLoginUserId();
        if (!userId.equals(infoNews.getCreateUserId())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //删除信息
        infoNewsMapper.deleteByPrimaryKey(req.getNewsId());
        return ServiceResult.ok(req.getNewsId());
    }

    /**
     * 【回收站中】根据信息发布ID把发布信息放到回收站中
     * @param req
     * @return
     */
    @Override
    public ServiceResult putRecycleInfoNewsByNewsId(InfoNewsIdReq req) {
        InfoNews infoNews = infoNewsMapper.selectByPrimaryKey(req.getNewsId());
        if (infoNews==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        String userId = getCurrentLoginUserId();
        if (!userId.equals(infoNews.getCreateUserId())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前时间
        Date nowDate = new Date();
        InfoNews updateInfoNews = new InfoNews();
        updateInfoNews.setNewsId(req.getNewsId());
        updateInfoNews.setIsDelete(SystemEnum.IS_DELETE.YES.getKey());
        updateInfoNews.setUpdateUserId(userId);
        updateInfoNews.setDeleteTime(nowDate);
        updateInfoNews.setUpdateTime(nowDate);
        infoNewsMapper.updateByPrimaryKeySelective(updateInfoNews);
        return ServiceResult.ok(req.getNewsId());
    }

    /**
     * 【把回收站中的信息恢复】根据信息发布ID把回收站中的信息恢复
     * @param req
     * @return
     */
    @Override
    public ServiceResult recoveryRecycleInfoNewsByNewsId(InfoNewsIdReq req) {
        InfoNews infoNews = infoNewsMapper.selectByPrimaryKey(req.getNewsId());
        if (infoNews==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        String userId = getCurrentLoginUserId();
        if (!userId.equals(infoNews.getCreateUserId())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        InfoNews updateInfoNews = new InfoNews();
        updateInfoNews.setNewsId(req.getNewsId());
        updateInfoNews.setUpdateTime(new Date());
        updateInfoNews.setIsDelete(SystemEnum.IS_DELETE.NO.getKey());
        updateInfoNews.setUpdateUserId(userId);
        infoNewsMapper.updateByPrimaryKeySelective(updateInfoNews);
        return ServiceResult.ok(req.getNewsId());
    }

    /**
     * 【私有方法，辅助其他接口方法使用】 检查信息分类是否存在
     */
    private void checkInfoCategoryId(String categoryId,String tenantId) {
        if (StringUtils.isBlank(categoryId)){
            throw new DuoJuHeException(ErrorCodes.INFO_CATEGORY_NOT_EXIST);
        }
        InfoCategory infoCategory = infoCategoryMapper.selectByPrimaryKey(categoryId);
        if(infoCategory==null || !tenantId.equals(infoCategory.getTenantId())){
            throw new DuoJuHeException(ErrorCodes.INFO_CATEGORY_NOT_EXIST);
        }
    }
}
